<template>
  <DynamicDetailDialog
    v-model="visible"
    :title="`资产详情 - ${
      detailData?.file_name || detailData?.filename || '加载中...'
    }`"
    :groups="detailGroups"
    :loading="loading"
    width="1200px"
    :close-on-click-modal="false"
  >
    <!-- 风险评分自定义内容 -->
    <template #risk-score>
      <span class="risk-score-text">{{ detailData?.risk_score }} 分</span>
    </template>

    <!-- 风险因素自定义内容 -->
    <template #risk-factors>
      <div class="risk-factors">
        <div class="factors-title">风险因素:</div>
        <ul class="factors-list">
          <li v-for="(factor, index) in riskFactorsList" :key="index">
            • {{ factor }}
          </li>
        </ul>
      </div>
    </template>

    <!-- 文件列表自定义内容 -->
    <template #filelist>
      <el-table :data="detailData?.filelist" border max-height="300">
        <el-table-column prop="filename" label="文件名" min-width="300" />
        <el-table-column prop="ext" label="类型" width="100" align="center">
          <template #default="{ row }">
            <span v-if="row.ext">.{{ row.ext }}</span>
            <span v-else-if="row.isdir">目录</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="size" label="大小" width="120" align="right">
          <template #default="{ row }">
            <span v-if="row.size">{{ formatSize(parseInt(row.size)) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="isdir" label="类型" width="80" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.isdir" type="info" size="small">目录</el-tag>
            <el-tag v-else type="success" size="small">文件</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </template>
  </DynamicDetailDialog>
</template>

<script setup lang="ts">
import { computed, ref } from "vue";
import { ElMessage } from "element-plus";
import DynamicDetailDialog from "@/components/DynamicDetailDialog";
import type { DetailGroup } from "@/components/DynamicDetailDialog/types";

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  assetId: { type: Number, default: null },
  detailData: { type: Object, default: null },
  loading: { type: Boolean, default: false },
});

const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
}>();

const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit("update:modelValue", value),
});

const exportLoading = ref(false);
const detailData = computed(() => props.detailData);
const loading = computed(() => props.loading);

// 风险因素列表
const riskFactorsList = computed(() => {
  if (!detailData.value?.risk_factors) return [];
  try {
    const factors =
      typeof detailData.value.risk_factors === "string"
        ? JSON.parse(detailData.value.risk_factors)
        : detailData.value.risk_factors;

    if (Array.isArray(factors)) {
      return factors;
    } else if (typeof factors === "object" && factors.risk_factors) {
      return factors.risk_factors;
    }
    return [];
  } catch {
    return [];
  }
});

// 格式化文件大小
const formatSize = (bytes: number): string => {
  if (!bytes) return "0 B";
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`;
  if (bytes < 1024 * 1024 * 1024)
    return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
  return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
};

// 格式化数字（添加千分位）
const formatNumber = (num: number): string => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

// 获取分类文本
const getCategoryText = (category: number): string => {
  const categoryMap: Record<number, string> = {
    0: "全部",
    1: "视频",
    2: "音乐",
    3: "图片",
    4: "文档",
    5: "软件",
    6: "压缩包",
    7: "BT种子",
  };
  return categoryMap[category] || `分类${category}`;
};

// 获取风险分数样式类
const getRiskScoreClass = (score: number): string => {
  if (score >= 80) return "risk-critical";
  if (score >= 60) return "risk-high";
  if (score >= 40) return "risk-medium";
  return "risk-low";
};

// 获取风险等级类型
const getRiskLevelType = (
  level: string
): "success" | "warning" | "danger" | "info" => {
  const typeMap: Record<string, "success" | "warning" | "danger" | "info"> = {
    critical: "danger",
    high: "danger",
    medium: "warning",
    low: "success",
  };
  return typeMap[level] || "info";
};

// 获取风险等级文本
const getRiskLevelText = (level: string): string => {
  const textMap: Record<string, string> = {
    critical: "极高",
    high: "高",
    medium: "中",
    low: "低",
  };
  return textMap[level] || level || "-";
};

// 获取审核状态类型
const getReviewStatusType = (
  status: string
): "success" | "warning" | "danger" | "info" => {
  const typeMap: Record<string, "success" | "warning" | "danger" | "info"> = {
    pending: "info",
    confirmed: "success",
    ignored: "warning",
  };
  return typeMap[status] || "info";
};

// 获取审核状态文本
const getReviewStatusText = (status: string): string => {
  const textMap: Record<string, string> = {
    pending: "待处理",
    confirmed: "已确认",
    ignored: "已忽略",
  };
  return textMap[status] || status || "-";
};

// 获取处理状态文本
const getProcessStatusText = (status: string): string => {
  const textMap: Record<string, string> = {
    completed: "已完成",
    processing: "处理中",
    failed: "处理失败",
  };
  return textMap[status] || status || "-";
};

// 获取验证状态文本
const getVerificationStatusText = (status: string): string => {
  const textMap: Record<string, string> = {
    verified: "已验证",
    unverified: "未验证",
    verifying: "验证中",
  };
  return textMap[status] || status || "-";
};

// 详情分组配置
const detailGroups = computed<DetailGroup[]>(() => {
  if (!detailData.value) return [];

  const groups: DetailGroup[] = [
    // 基本信息
    {
      title: "基本信息",
      column: 3,
      border: true,
      items: [
        {
          key: "filename",
          label: "文件名称",
          value: detailData.value.file_name || detailData.value.filename || "-",
        },
        {
          key: "size",
          label: "文件大小",
          value: detailData.value.size_mb
            ? `${detailData.value.size_mb} MB`
            : detailData.value.size
            ? `${formatSize(detailData.value.size)} (${formatNumber(
                detailData.value.size
              )} 字节)`
            : "-",
        },
        {
          key: "file_type",
          label: "文件类型",
          value: detailData.value.ext
            ? `.${detailData.value.ext}${
                detailData.value.category
                  ? ` | 分类: ${getCategoryText(detailData.value.category)}`
                  : ""
              }`
            : "-",
        },
        {
          key: "asset_id",
          label: "资产ID",
          value: detailData.value.leak_id || detailData.value.id || "-",
        },
        {
          key: "detected_time",
          label: "检测时间",
          value:
            detailData.value.detected_time ||
            detailData.value.created_time ||
            "-",
        },
        {
          key: "api_user",
          label: "API用户",
          value: detailData.value.api_type
            ? `${detailData.value.api_type}${
                detailData.value.api_updatetime
                  ? ` | 更新: ${detailData.value.api_updatetime}`
                  : ""
              }`
            : "-",
        },
        {
          key: "department",
          label: "责任部门",
          value:
            detailData.value.confirmed_department ||
            detailData.value.responsible_department ||
            "-",
        },
        {
          key: "person",
          label: "责任人",
          value:
            detailData.value.confirmed_person ||
            detailData.value.responsible_person ||
            "-",
        },
        ...(detailData.value.source_task_id
          ? [
              {
                key: "source_task",
                label: "来源任务",
                value:
                  detailData.value.source_task_name ||
                  `任务 #${detailData.value.source_task_id}`,
              },
            ]
          : []),
      ],
    },
  ];

  // 风险评估
  if (
    detailData.value.risk_score !== null &&
    detailData.value.risk_score !== undefined
  ) {
    groups.push({
      title: "风险评估 (AI智能分析)",
      column: 2,
      border: true,
      items: [
        {
          key: "risk_score",
          label: "综合风险评分",
          type: "custom" as const,
          slot: "risk-score",
        },
        {
          key: "risk_level",
          label: "风险等级",
          type: "tag" as const,
          value: `${getRiskLevelText(detailData.value.risk_level)}风险`,
          tagType: getRiskLevelType(detailData.value.risk_level),
          tagSize: "small",
        },
        ...(detailData.value.scored_at
          ? [
              {
                key: "scored_at",
                label: "评分时间",
                value: detailData.value.scored_at,
              },
            ]
          : []),
        ...(detailData.value.scene_name
          ? [
              {
                key: "scene_name",
                label: "场景匹配",
                value: `${detailData.value.scene_name}${
                  detailData.value.scene_weight
                    ? ` (权重: ${detailData.value.scene_weight})`
                    : ""
                }`,
              },
            ]
          : []),
        ...(detailData.value.asset_keyword || detailData.value.keyword
          ? [
              {
                key: "keyword",
                label: "匹配关键词",
                value:
                  detailData.value.asset_keyword || detailData.value.keyword,
              },
            ]
          : []),
        ...(riskFactorsList.value.length > 0
          ? [
              {
                key: "risk_factors",
                label: "风险因素",
                type: "custom" as const,
                slot: "risk-factors",
                span: 2,
              },
            ]
          : []),
      ],
    });
  }

  // 审核状态
  groups.push({
    title: "审核状态",
    column: 2,
    border: true,
    items: [
      {
        key: "review_status",
        label: "当前状态",
        type: "tag",
        value: getReviewStatusText(detailData.value.review_status),
        tagType: getReviewStatusType(detailData.value.review_status),
        tagSize: "small",
      },
      {
        key: "processed_status",
        label: "处理状态",
        value: getProcessStatusText(detailData.value.processed_status),
      },
      {
        key: "verification_status",
        label: "验证状态",
        value: getVerificationStatusText(detailData.value.verification_status),
      },
      ...(detailData.value.quality_score
        ? [
            {
              key: "quality_score",
              label: "质量评分",
              value: `${detailData.value.quality_score} 分${
                detailData.value.confidence_level
                  ? ` | 置信度: ${(
                      detailData.value.confidence_level * 100
                    ).toFixed(0)}%`
                  : ""
              }`,
            },
          ]
        : []),
      ...(detailData.value.is_ignored && detailData.value.ignored_reason
        ? [
            {
              key: "ignored_reason",
              label: "忽略原因",
              value: detailData.value.ignored_reason,
            },
          ]
        : []),
      ...(detailData.value.is_ignored && detailData.value.ignored_time
        ? [
            {
              key: "ignored_time",
              label: "忽略时间",
              value: detailData.value.ignored_time,
            },
          ]
        : []),
      ...(detailData.value.review_comment
        ? [
            {
              key: "review_comment",
              label: "审核意见",
              value: detailData.value.review_comment,
            },
          ]
        : []),
      ...(detailData.value.review_time
        ? [
            {
              key: "review_time",
              label: "审核时间",
              value: detailData.value.review_time,
            },
          ]
        : []),
    ],
  });

  // 文件列表
  if (
    detailData.value.filelist &&
    Array.isArray(detailData.value.filelist) &&
    detailData.value.filelist.length > 0
  ) {
    groups.push({
      title: "文件列表",
      column: 1,
      border: false,
      items: [
        {
          key: "filelist",
          label: "文件列表",
          type: "custom" as const,
          slot: "filelist",
          span: 1,
        },
      ],
    });
  }

  return groups;
});

// 导出详情
const handleExport = async () => {
  if (!props.assetId) {
    ElMessage.warning("资产ID不存在");
    return;
  }

  exportLoading.value = true;
  try {
    // TODO: 实现资产详情导出功能
    ElMessage.info("导出功能开发中");
  } catch (error: any) {
    ElMessage.error(error?.message || "导出失败");
  } finally {
    exportLoading.value = false;
  }
};

// 取消
const handleCancel = () => {
  emit("update:modelValue", false);
};
</script>

<style scoped lang="scss">
.risk-score-text {
  color: #f56c6c;
  font-weight: 500;
  font-size: 14px;
}

.risk-factors {
  padding: 15px;
  background-color: #fff7e6;
  border: 1px solid #ffe58f;
  border-radius: 4px;

  .factors-title {
    font-weight: 500;
    color: #303133;
    margin-bottom: 10px;
  }

  .factors-list {
    margin: 0;
    padding-left: 20px;
    color: #606266;

    li {
      margin: 5px 0;
      line-height: 1.6;
    }
  }
}
</style>
